package com.cyc.controller;

import com.alibaba.fastjson.JSON;
import com.cyc.config.AlipayConfig;
import com.cyc.entity.Order;
import com.cyc.entity.Role;
import com.cyc.entity.User;
import com.cyc.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    RoleService roleService;

    @Autowired
    protected  RoleRefService roleRefService;

    @Autowired
    protected UserService userService;

    @Autowired
    AddressService addressService;

    @Autowired
    CommentService commentService;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDetailService orderDetailService;

    @RequestMapping("login")
    @ResponseBody
    public String login(User user, HttpSession session){
        Map<String,Object> map=new HashMap<>();

        try{
            Subject subject=SecurityUtils.getSubject();
            UsernamePasswordToken token=new UsernamePasswordToken(user.getLoginname(),user.getPassword());
            subject.login(token);

            //认证成功
            User loginUser=(User) SecurityUtils.getSubject().getPrincipal();
            session.setAttribute("user",loginUser);
            map.put("code",1);
            map.put("msg","登陆成功");
            map.put("username",loginUser.getUsername());



        }catch (UnknownAccountException e){
            map.put("code",0);
            map.put("msg","用户名错误");
        }catch (IncorrectCredentialsException e){
            map.put("code",0);
            map.put("msg","密码错误");
        }catch (AuthenticationException e){
            map.put("code",0);
            map.put("msg","联系管理员");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/logout")
    public String loginout(HttpSession session){
        session.removeAttribute("user");
        SecurityUtils.getSubject().logout();
        return "index";
    }


    @RequestMapping("/register")
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    public String register(User user){
        Map<String, Object> map=new HashMap<>();

        try {
            userService.insert(user);
            Map<String, Object> ddd=new HashMap<>();
            ddd.put("userId",user.getId());
            ddd.put("createTime",new Date());
            roleRefService.insert(ddd);
            Map<String, Object> sss=new HashMap<>();
            sss.put("address",user.getAddress());
            sss.put("userId",user.getId());
            int i = addressService.insertByuserId(sss);
            if (i>0){
                map.put("code",1);
                map.put("msg","注册成功");
            }else {
                map.put("code",0);
                map.put("msg","注册失败");
            }
        }catch (Exception e){
            map.put("code",0);
            map.put("msg","注册失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return JSON.toJSONString(map);
    }

    @RequestMapping("all")
    @ResponseBody
    public String selectAll(Integer page,Integer limit){
        Map<String, Object> map=new HashMap<>();
        PageHelper.startPage(page,limit);
        List<User> list = userService.selectAll();
        PageInfo pageInfo=new PageInfo(list);
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",pageInfo.getTotal());
        map.put("data",list);
        return JSON.toJSONString(map);
    }

    @RequestMapping("/del")
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    public String del(Integer id){
        Map<String, Object> map=new HashMap<>();
        for (Order order : orderService.selectByUserId(id)) {
            orderDetailService.deleteByOrderId(order.getId());
        }
        orderService.deleteByUserId(id);
        addressService.deleteByUserId(id);
        commentService.deleteByUserId(id);
        int i = userService.deleteByPrimaryKey(id);
        if (i>0){
            map.put("msg","删除成功");
        }else {
            map.put("msg","删除失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/update")
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    public String update(User user){
        Map<String, Object> map=new HashMap<>();
        Map<String, Object> sss=new HashMap<>();
        sss.put("address",user.getAddress());
        sss.put("userId",user.getId());
        addressService.updateByUserId(sss);
        int i = userService.updateByPrimaryKey(user);
        if (i>0){
            map.put("msg","修改成功");
        }else {
            map.put("msg","修改失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JSON.toJSONString(map);
    }
}
